package com.wiloon.java.network.network.netty.tls;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.security.KeyStore;

public class TlsClient {
    private Logger logger = LoggerFactory.getLogger(TlsClient.class);
    public static String HOST = "127.0.0.1";
    public static int PORT = 9000;


    public static void main(String[] args) {
        TlsClient tlsClient = new TlsClient();
        tlsClient.run();
    }

    public void run() {

        Bootstrap bootstrap = new Bootstrap();

        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        bootstrap.group(eventLoopGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
                pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
                pipeline.addLast("handler", new ClientHandler());

                KeyStore keyStore = KeyStore.getInstance("JKS");
                keyStore.load(new FileInputStream("/home/roy/workspace/tmp/cChat.jks"), "cNetty".toCharArray());
                TrustManagerFactory tf = TrustManagerFactory.getInstance("SunX509");
                tf.init(keyStore);
                SSLContext context = SSLContext.getInstance("TLSv1.2");
                context.init(null, tf.getTrustManagers(), null);
                SSLEngine engine = context.createSSLEngine();
                engine.setUseClientMode(true);
                pipeline.addFirst("ssl", new SslHandler(engine));

            }
        });

        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        try {
            Channel channel = bootstrap.connect(HOST, PORT).sync().channel();
            logger.info("connected.");
            String msg = "msg0";
            channel.writeAndFlush("msg0").sync();
            logger.info("msg sent:{}", msg);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    class ClientHandler extends SimpleChannelInboundHandler<Object> {
        private Logger logger = LoggerFactory.getLogger(ClientHandler.class);

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
            logger.info("channel read, msg from server:{}", msg);
        }


    }


}
